<template>
  <div :style="newStyle">
    <span v-if="$attrs.onlyShow">{{getCascaderText($attrs)}}</span>
    <el-cascader
      style="width:100%"
      v-else
      v-model="formValue"
      v-bind="$attrs"
      @blur="onBlur"
      @focus="onFocus"
      @clear="onClear"
      @change="$emit('validate',$event)"
      :options="resData"
      :props="{...dataObj.props,multiple:$attrs.multiple}"
    ></el-cascader>
  </div>
</template>

<script>
import { treeToArray } from "../../../utils";
import { comMixin } from "../../../utils/comMixins";
export default {
  mixins: [comMixin],
  name: "form-cascader",
  model: {
    prop: "value", // 绑定的值，通过父组件传递
    event: "update",
  },
  props: ["modelValue"],
  computed: {
    formValue: {
      get() {
        return this.modelValue;
      },
      set(val) {
        this.$emit("update:modelValue", val);
        this.onChange(val);
      },
    },
  },
  methods: {
    // 根据级联的值获取级联的显示文本
    getCascaderText(formItem) {
      const props = this.dataObj.props;
      const formValue = this.modelValue;
      const options = treeToArray(this.resData, props.children);
      let path = [];
      formValue?.forEach((value) => {
        const active = options.find((item) => item[props.value] == value);
        if (active) path.push(active[props.label]);
      });
      // 间隔符
      const separator = formItem.separator;
      // 是否展示全路径
      const showAllLevels = formItem["showAllLevels"];
      return showAllLevels ? path.join(separator) : path[path.length - 1];
    },
  },
};
</script>

<style lang="scss" scoped></style>
